package com.lh.pattern.proxy;

import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

class Proxy {
	public static Object newProxyIntenct(Class infac, InvocationHandler h)
			throws Exception {
		String br = "\r\n";

		String methString = "";
		Method[] method = infac.getMethods();

		for (Method m : method) {
			methString = "  @Override" + br + "   public void " + m.getName()
					+ "() {" + br + "       try {" + br + "       Method md ="
					+ infac.getName() + ".class.getMethod(\"" + m.getName()
					+ "\");" + br + "       h.invoke(this,md);" + br
					+ "       }catch (Exception e){ " + br
					+ "           e.printStackTrace();" + br + "       }" + br
					+ "   }";
		}

		String src = "package com.lh.pattern.proxy;" + br
				+ "import java.lang.reflect.Method;" + br
				+ "public class $Proxy implements " + infac.getName() + "{"
				+ br + "   private com.lh.pattern.proxy.InvocationHandler h;"
				+ br + "   public $Proxy(InvocationHandler h) {" + br
				+ "       super();" + br + "       this.h = h;" + br + "   }"
				+ br + br + methString + br + "}";

		// 生成java文件
		String fileName = System.getProperty("user.dir") + // 获取到项目的根路径
				"/src/com/lh/pattern/proxy/$Proxy.java";
		System.out.println(fileName);
		File file = new File(fileName);
		FileWriter fWriter = new FileWriter(file);
		fWriter.write(src);
		fWriter.flush();
		fWriter.close();

		// 生成class文件,jdk6提供的工具类
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		// System.out.println(compiler.getClass().getName());
		StandardJavaFileManager fileManager = compiler.getStandardFileManager(
				null, null, null);
		Iterable units = fileManager.getJavaFileObjects(fileName);
		CompilationTask task = compiler.getTask(null, fileManager, null, null,
				null, units);
		task.call();
		fileManager.close();

		// 装载到内存,生成新对象
		URL[] urls = new URL[] { new URL("file:/"
				+ System.getProperty("user.dir") + "/src") };
		URLClassLoader loader = new URLClassLoader(urls);
		Class c = loader.loadClass("com.lh.pattern.proxy.$Proxy");

		// 通过有参的构造器反射生成代理类的实例
		Constructor ctr = c.getConstructor(InvocationHandler.class);
		Object obj = (Object) ctr.newInstance(h);
		return obj;

	}

}